package com.leo.chapter07;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 不支持关闭的日志服务
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class LogWriter {
    private final BlockingQueue<String> queue;
    private final LoggerThread logger;

    public LogWriter(Writer writer){
        this.queue = new LinkedBlockingQueue<>(100);
        this.logger = new LoggerThread((PrintWriter) writer);
    }

    public void start() { logger.start(); }

    public void log(String msg) throws InterruptedException{ queue.put(msg); }

    //真正干活的线程
    private class LoggerThread extends Thread{
        private final PrintWriter writer;
        private LoggerThread(PrintWriter writer) {
            this.writer = writer;
        }

        public void run(){
            try {
                while (true){
                    writer.write(queue.take());
                }
            } catch (InterruptedException e) {
                //忽略
            }finally {
                writer.close();
            }
        }
    }
}
